﻿using System.Collections.Concurrent;
using System.Reflection;

namespace Basic.EventBus.Attributes
{
    [AttributeUsage(AttributeTargets.Class)]
    public class EventTopicAttribute : Attribute
    {
        public string Group { get; set; }
        public string Key { get; set; }
        public string Topic { get; set; }
        /// <summary>
        /// 队列持久化
        /// </summary>
        public bool Durable { get; set; }
        /// <summary>
        /// 字段填充默认参数
        /// </summary>
        public bool AutoFill { get; set; }

        public void Parse(Type type)
        {
            if (AutoFill)
            {
                Durable = true;
                if (Topic == null) Topic = type.FullName;
                if (Group == null) Group = type.Name;
                if (Key == null) Key = type.Name;
            }
        }

        #region Static
        private static ConcurrentDictionary<Guid, EventTopicAttribute> AttrDict = new ConcurrentDictionary<Guid, EventTopicAttribute>(4, 16);

        public static EventTopicAttribute GetCurrentAttribute(Type type)
        {
            if (AttrDict.TryGetValue(type.GUID, out var attribute))
                return attribute;

            attribute = type.GetCustomAttribute<EventTopicAttribute>();
            if (attribute != null)
            {
                attribute.Parse(type);
                AttrDict.TryAdd(type.GUID, attribute);
            }
            return attribute;
        }

        #endregion

    }

}